package com.jifen.common;

import com.jifen.constant.ErrorCode;
import com.jifen.user.dao.UserDao;
import com.jifen.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/jf/{version}/authcode")
public class AuthCodeController {

    @Resource
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    UserDao userDao;

    /**
     * 发送注册短信验证码
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public Result sendRegister(String mobile) {
        if(StringUtils.isNotBlank(mobile)){
            if(userDao.getByMobile(mobile)!=null){
                throw new MyException(ErrorCode.MOBILE_ALREADY_REG);
            }
            //Map<String, String> map = SmsUtils.sendSms(mobile, "SMS_149385676");
            //String authcode = map.get("value");
            String authcode = "123456";
            if (StringUtils.isNotBlank(authcode)) {
                redisTemplate.opsForValue().set("sms_authcode_" + mobile, authcode, 15, TimeUnit.MINUTES);
            }else {
                //return CommonResult.createErrorResult(map.get("msg"));
            }
        }
        return CommonResult.createSuccessResult();
    }

    /**
     * 发送短信验证码
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/send")
    @ResponseBody
    public Result send(String mobile) {
/*        if (userDao.getByMobile(mobile) == null) {
            throw new MyException(ErrorCode.MOBILE_NOT_REG);
        }*/
        Map<String, String> map = SmsUtils.sendSms(mobile, "SMS_169112494", null);
        String authcode = map.get("value");
        //String authcode = "123456";
        if (StringUtils.isNotBlank(authcode)) {
            redisTemplate.opsForValue().set("sms_authcode_" + mobile, authcode, 15, TimeUnit.MINUTES);

        } else {
            //return CommonResult.createErrorResult(map.get("msg"));
        }
        return CommonResult.createSuccessResult();
    }


}
